# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
crypto  = require 'crypto'
router = express.Router()
module.exports = router

router.get '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select * from web_email limit 1", defer err, result
    if err then done(client); return next(err)
    if result.rows.length == 0
        await client.query \
            "insert into web_email values (
                default, '', 465, '', '', '', true, 3
            )", defer err, result
        if err then done(client); return next(err)
    done()
    record = result.rows[0]
    res.render 'email', record: record or { smtp_ssl: true }


router.post '/edit', (req, res, next) ->
    for k in ['smtp_host', 'smtp_port', 'smtp_ssl', 'retry_cnt',
        'smtp_from', 'smtp_name']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update web_email set smtp_host = $1, smtp_port = $2,
            smtp_ssl = $3, retry_cnt = $4, smtp_from = $5, smtp_name = $6,
            notify_mail = $7, notify_level = $8, notify_recips = $9", [
            req.body.smtp_host,
            req.body.smtp_port,
            req.body.smtp_ssl,
            req.body.retry_cnt,
            req.body.smtp_from,
            req.body.smtp_name,
            req.body.notify_mail is 'true',
            parseInt(req.body.notify_level),
            req.body.notify_recips,
        ], defer err, result
    if err then done(client); return next(err)

    if req.body.smtp_passwd and req.body.smtp_passwd.length > 0
        secure_key = Buffer.from settings.secure_key, 'hex'
        if secure_key.length isnt 16
            done()
            return next new Error('安全密钥配置错误，必须由 32 位[0-9A-F]数字组成')

        cipher = crypto.createCipheriv 'des-ede', secure_key, new Buffer('')
        passwd = cipher.update req.body.smtp_passwd, 'utf8', 'hex'
        passwd += cipher.final 'hex'
        await client.query \
            "update web_email set smtp_passwd = $1", [
                passwd
            ], defer err, result
        if err then done(client); return next(err)
    done()
    res.redirect '/email'
